<template>
  <div id="FractionalSegment" style="width: 1600px; height: 400px"></div>
</template>
<script>
import echarts from "echarts";
import request from "@/utils/request";
import eventBus from "./eventBus.js";
export default {
  name: "FractionalSegment",
  props: {
    totalScore: {
      default: 0
    }
  },
  data() {
    return {
      list: [],
      chart: null
    };
  },
  mounted() {
    eventBus.$on("getList", e => {
      this.list = e;
      let tscore = Math.ceil(this.totalScore / 10) * 10; // 向上取整
      let XData = [];
      for (let index = 0; index < tscore / 10; index++) {
        XData.push(`${index * 10}-${(index + 1) * 10}`);
      }
      let YData = [];
      for (let i = 0; i < XData.length; i++) {
        YData[i] = 0;
      }
      this.list.forEach(value => {
        YData.forEach((item, index) => {
          let front = XData[index].match(/(\S*)-/)[1]; // 截取"-"前的内容
          let after = XData[index].match(/-(\S*)/)[1]; // 截取"-"后的内容
          if (value.score > front * 1 && value.score <= after * 1) {
            YData[index] += (1 / this.list.length) * 100;
          }
        });
      });
      this.initChart(XData, YData);
    });
  },
  methods: {
    initChart(XData, YData) {
      let option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            crossStyle: {
              color: "#999"
            }
          }
        },

        grid: {
          x: 0,
          y: 0,
          x2: 0,
          y2: 0,
          top: "20%",
          left: "3%",
          right: "3%",
          bottom: "0%",
          containLabel: true
        },
        xAxis: [
          {
            name: "分数",
            type: "category",
            data: XData,
            axisPointer: {
              type: "shadow"
            }
          }
        ],
        yAxis: [
          {
            name: "人数占例(%)",
            type: "value",
            min: 0,
            max: 100,
            interval: 10,
            axisLabel: {
              formatter: "{value} "
            }
          }
        ],
        series: [
          {
            name: "人数占例(%)",
            type: "bar",
            itemStyle: {
              normal: {
                color: "#19d4ae"
              }
            },
            data: YData
          }
        ]
      };
      this.chart = echarts.init(document.getElementById("FractionalSegment"));
      this.chart.setOption(option);
      window.onresize = this.chart.resize();
    }
  }
};
</script>
<style scoped lang="scss"></style>
